<template>
  <dragSize
    v-for="item in dialogList"
    :key="item.RID"
    :kvm="item"
    :drag-min-height="500"
    :drag-min-width="740"
    :p-index="item.RID"
    :is-show="true"
    :z-index="item.zIndex || 10000"
    @selectItem="topDialog"
    @openNew="openFunc"
    @close="beforeClose"
  >
    <div class="dialog_content" @click="topDialog">
      <div style="height: 100%">
        <div class="terminalOption space-x-1 flex flex-row">
          <div style="color: #444">
            是否只读:
            <el-switch
              v-model="radioMap[item.RID].read"
              @change="changeVirtual(item)"
            />
          </div>
        </div>
        <div class="virtualiframe" v-loading="loading">
          <div
            :class="[
              'iframeMain',
              radioMap[item.RID].read ? 'divReadonly' : '',
            ]"
          >
            <Terminal :url="url"></Terminal>
            <!-- <iframe
              :id="'dockerTerminal' + item.RID"
              :src="
                origin +
                '/#/dockerManage/?id=' +
                item.id +
                '&url=' +
                url +
                '&iframe=' +
                true
              "
              width="100%"
              height="100%"
            /> -->
          </div>
        </div>
      </div>
    </div>
  </dragSize>
</template>
<script setup>
import { nextTick, onMounted, onUnmounted, ref, defineExpose } from 'vue';
import dragSize from './dragSize.vue';
import Terminal from '@/views/simulation/dockerManage/index.vue';
const emit = defineEmits(['closeDialog', 'topDialog']);
const props = defineProps({
  dialogList: {
    default: function () {
      return [];
    },
    type: Array,
  },
});
//保存read、loading等信息
const radioMap = ref({});
const origin = ref(null);
const url = ref(null);
const hostOrigin = ref(null);
const activeItem = ref(null);
const mode = import.meta.env.MODE;
origin.value =
  mode === 'development' ? 'https://172.17.0.29' : window.location.origin;
// origin.value = 'https://172.17.0.29';
hostOrigin.value = window.location.host;

const loading = ref(false);
// hostOrigin.value = '172.16.2.155';
const beforeClose = item => {
  closeFunc(item);
  emit('closeDialog', item);
};
onMounted(async () => {
  window.addEventListener('message', messageFunc);
});
onUnmounted(async () => {
  window.removeEventListener('message', messageFunc);
});
const messageFunc = async event => {
  const message = event.data;
  if (!message) {
    setTimeout(() => {
      closeFunc(activeItem.value);
      emit('closeDialog', activeItem.value);
    }, 1000);
  }
  if (message === 'Docker Websocket Connection Failed!') {
    setTimeout(() => {
      closeFunc(activeItem.value);
      emit('closeDialog', activeItem.value);
    }, 1000);
  }
};
const topDialog = item => {
  activeItem.value = item;
  emit('topDialog', item);
};
function focusFunc(item) {
  let iframe = document.getElementById('dockerTerminal' + item.RID);
  // if (iframe.contentWindow && !radioMap.value[item.RID].read) {
  //   // 在此处执行方法加载完毕后的代码
  //   iframe.focus();
  //   loading.value = false;
  // }

  iframe.focus();
  loading.value = false;
}
function closeFunc(item) {
  // let iframe = document.getElementById('dockerTerminal' + item.RID);
  // var iframeDoc = iframe.contentDocument || iframe.contentWindow.top.document;
  // iframe && iframe.removeEventListener('load', focusFunc(item));
  // iframeDoc.removeEventListener('click', function () {
  //   topDialog(item);
  //   focusFunc(item);
  // });
  // destroyIframe('dockerTerminal' + item.RID);
  delete radioMap.value[item.RID];
}
function destroyIframe(iframeID) {
  var iframe = document.getElementById(iframeID);
  //把iframe指向空白页面，这样可以释放大部分内存。
  iframe.src = 'about:blank';
  try {
    iframe.contentWindow.document.write('');
    iframe.contentWindow.document.clear();
  } catch (e) {}
  //把iframe从页面移除
  iframe.parentNode.removeChild(iframe);
}
const openFunc = async item => {
  radioMap.value[item.RID] = { read: false, loading: true };
  const mode = import.meta.env.MODE;
  url.value =
    mode === 'development'
      ? `ws://172.17.0.29:12001/simulation/scene/scene/${item['id']}/instance/${item['RID']}/console/`
      : `wss://${hostOrigin.value}/api/topo/simulation/scene/scene/${item['id']}/instance/${item['RID']}/console/`;
  // url.value = `ws://172.17.0.29:12001/simulation/scene/scene/${item['id']}/instance/${item['RID']}/console/`;
  activeItem.value = item;
  // await setIfameInfo(item);
};
function setIfameInfo(item) {
  nextTick(() => {
    const iframeWindow = document.getElementById(
      'dockerTerminal' + item.RID,
    ).contentWindow;
    let iframe = document.getElementById('dockerTerminal' + item.RID);
    iframe.onload = function () {
      var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      iframeDoc.addEventListener('click', function () {
        topDialog(item);
        focusFunc(item);
      });
    };
    iframe && iframe.addEventListener('load', focusFunc(item));
    if (radioMap.value[item.RID].read) {
      iframeWindow.addEventListener('keydown', readonlyDocument);
      iframeWindow.addEventListener('mousedown', readonlyDocument);
    } else {
      iframeWindow.removeEventListener('keydown', readonlyDocument);
      iframeWindow.removeEventListener('mousedown', readonlyDocument);
      focusFunc(item);
    }
  });
  function readonlyDocument(event) {
    event && event.preventDefault();
  }
}
defineExpose({
  openFunc,
});
</script>

<style lang="scss" scoped>
.divReadonly {
  pointer-events: none;
  cursor: default;
}

.dialog_content {
  width: 100%;
  height: 100%;
}
.virtualiframe {
  padding: unset;
  border-radius: unset;
  width: 100%;
  height: calc(100% - 35px);
  overflow: auto;
  .iframeMain {
    width: 100%;
    height: 100%;
    &.readonly {
      iframe {
        pointer-events: none;
        -moz-user-select: none; /*火狐*/
        -webkit-user-select: none; /*webkit浏览器*/
        -ms-user-select: none; /*IE10*/
        //-khtml-user-select: none; /*早期浏览器*/
        user-select: none;
      }
    }
  }
}
</style>
